package javaMSCRM;
import java.awt.BorderLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import com.microsoft.schemas.crm._2006.query.AllColumns;
import com.microsoft.schemas.crm._2006.webservices.Key;
import com.microsoft.schemas.crm._2006.webservices.Picklist;
import com.microsoft.schemas.crm._2007.webservices.Lead;
import com.microsoft.schemas.crm._2007.webservices.CreateDocument;
import com.microsoft.schemas.crm._2007.webservices.CreateResponseDocument;
import com.microsoft.schemas.crm._2007.webservices.DeleteDocument;
import com.microsoft.schemas.crm._2007.webservices.EntityName;
import com.microsoft.schemas.crm._2007.webservices.RetrieveDocument;
import com.microsoft.schemas.crm._2007.webservices.TargetUpdateLead;
import com.microsoft.schemas.crm._2007.webservices.UpdateDocument;
import com.microsoft.schemas.crm._2007.webservices.UpdateResponseDocument;
import com.microsoft.schemas.crm._2007.webservices.CreateDocument.Create;
import com.microsoft.schemas.crm._2007.webservices.CreateResponseDocument.CreateResponse;
import com.microsoft.schemas.crm._2007.webservices.DeleteDocument.Delete;
import com.microsoft.schemas.crm._2007.webservices.RetrieveDocument.Retrieve;
import com.microsoft.schemas.crm._2007.webservices.UpdateDocument.Update;
import com.microsoft.schemas.crm._2007.webservices.TargetCreateLead;

import net.miginfocom.layout.AC;
import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;

/**
 * 
 */

/**
 * @author Zoran IVANOV
 *
 */
public class JavaMSCRMLead extends Form {
	Lead record = null;
	JTextField 	JTFTopic=new JTextField(""),
				JTFFirstName=new JTextField(""),
				JTFLastName=new JTextField(""),
				JTFTitle=new JTextField(""),
				JTFCompanyName=new JTextField(""),
				JTFBusinessPhone=new JTextField(""),
				JTFEmail=new JTextField("");
	JComboBox JCBRating;
	String[] RatingItemsList = new String[]{
			"Hot",
			"Warm",
			"Cold"};
	JButton SaveButton,DeleteButton;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * @param JavaMSCRM
	 */
	public JavaMSCRMLead(JavaMSCRM JavaMSCRM) {
		super(JavaMSCRM);
		setTitle("New Lead");
		JScrollPane FormScrollPane = new JScrollPane(setupFields());
		FormScrollPane.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		add(FormScrollPane, BorderLayout.CENTER);
		pack();
		setVisible(true);
	}
	
	/**
	 * @param JavaMSCRM
	 * @param Id
	 */
	public JavaMSCRMLead(JavaMSCRM JavaMSCRM, String Id) {
		super(JavaMSCRM, Id);
		try {
	        RetrieveDocument rd = RetrieveDocument.Factory.newInstance();  
	        Retrieve r = Retrieve.Factory.newInstance();	        
	        r.setEntityName(EntityName.LEAD.toString());
	        r.setId(Id);
	        r.setColumnSet(AllColumns.Factory.newInstance());	        
	        rd.setRetrieve(r);
	        record = (Lead) JavaMSCRM.stub.Retrieve(rd,  JavaMSCRM.catd, null, null).getRetrieveResponse().getRetrieveResult();
		}  
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString());
		}		
		setTitle("Lead: " + record.getSubject());
		JScrollPane FormScrollPane = new JScrollPane(setupFields());
		FormScrollPane.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		add(FormScrollPane, BorderLayout.CENTER);
		pack();
		setVisible(true);
	}
	
	/**
	 * @return JPanel
	 */
	private JPanel setupFields(){
		LC layC = new LC().wrap();
		AC colC = new AC().align("right", 0).fill(1, 3).grow(100, 1, 3).align("right", 2).gap("15", 1);
		AC rowC = new AC().index(6).gap("15!").align("top").grow(100, 0);	
		JPanel form = new JPanel(new MigLayout(layC, colC, rowC));		
		JPanel formContainer = new JPanel(new MigLayout(layC, colC, rowC));		
		formContainer.add(form, BorderLayout.NORTH);			
		form.setBorder(BorderFactory. createEmptyBorder(0,0,0,0));
		//Create TextFields
		
		try{JTFTopic = new JTextField(record.getSubject());}catch (Exception e) {}
		try{JTFFirstName = new JTextField(record.getFirstname());}catch (Exception e) {}
		try{JTFLastName = new JTextField(record.getLastname());}catch (Exception e) {}
		try{JTFCompanyName = new JTextField(record.getCompanyname());}catch (Exception e) {}
		try{JTFTitle = new JTextField(record.getJobtitle());}catch (Exception e) {}
		try{JTFBusinessPhone = new JTextField(record.getTelephone1());}catch (Exception e) {}
		try{JTFEmail = new JTextField(record.getEmailaddress1());}catch (Exception e) {}
		
		JCBRating = new JavaMSCRMComboBox(RatingItemsList, false);
		try{JCBRating.setSelectedItem(RatingItemsList[record.getLeadqualitycode().getIntValue()-1]);}catch (Exception e) {}


		addSeparator(form, "General");		
		
		form.add(new JavaMSCRMLabel("Topic", true));		
		form.add(JTFTopic, "w 200:100:");
		form.add(new JavaMSCRMLabel("First Name", false));		
		form.add(JTFFirstName, "w 200:100:");
		form.add(new JavaMSCRMLabel("Last Name", false));	
		form.add(JTFLastName, "w 200:100:");		
		form.add(new JavaMSCRMLabel("Title", false));	
		form.add(JTFTitle, "w 200:100:");
		form.add(new JavaMSCRMLabel("Company Name", false));	
		form.add(JTFCompanyName, "w 200:100:");
		form.add(new JavaMSCRMLabel("Rating", false));	
		form.add(JCBRating, "w 200:100:");		
		
		addSeparator(form, "Contact Information");

		form.add(new JavaMSCRMLabel("Business Phone", false));	
		form.add(JTFBusinessPhone, "w 200:100:");
		form.add(new JavaMSCRMLabel("E-mail", false));	
		form.add(JTFEmail, "w 200:100:");
		
		return formContainer;
	}
	
	/* (non-Javadoc)
	 * @see JavaMSCRMForm#createRecord()
	 */
	public void createRecord(){
		String EntityId = "";
		try {
			TargetCreateLead targetEntity = TargetCreateLead.Factory.newInstance();
			Lead Entity = targetEntity.addNewLead();
			
			Entity.setSubject(JTFTopic.getText());
			Entity.setFirstname(JTFFirstName.getText());
			Entity.setLastname(JTFLastName.getText());
			Entity.setJobtitle(JTFTitle.getText());
			Entity.setCompanyname(JTFCompanyName.getText());

			Picklist ctc = Picklist.Factory.newInstance();
			ctc.setIntValue(JCBRating.getSelectedIndex()+1);
			Entity.setLeadqualitycode(ctc);
			
			Entity.setTelephone1(JTFBusinessPhone.getText());
			Entity.setEmailaddress1(JTFEmail.getText());
					
			CreateDocument cd = CreateDocument.Factory.newInstance();
			Create create = Create.Factory.newInstance();
			create.setEntity(Entity);
			cd.setCreate(create);
		
			CreateResponseDocument crd = JavaMSCRM.stub.Create(cd, JavaMSCRM.catd, null, null);
			CreateResponse cr = crd.getCreateResponse();
			EntityId = cr.getCreateResult();
		}  
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString());
		}
		
		if(EntityId != ""){
			new Leads(JavaMSCRM);
			new JavaMSCRMLead(JavaMSCRM,EntityId);
			dispose();
		}else{
			JOptionPane.showMessageDialog(null, "There was an error while creating the record!");
		}		
	}
	
	/* (non-Javadoc)
	 * @see JavaMSCRMForm#updateRecord()
	 */
	public void updateRecord(){
		try {
			TargetUpdateLead targetEntity = TargetUpdateLead.Factory.newInstance();
			Lead Entity = targetEntity.addNewLead();

			Entity.setSubject(JTFTopic.getText());
			Entity.setFirstname(JTFFirstName.getText());
			Entity.setLastname(JTFLastName.getText());
			Entity.setJobtitle(JTFTitle.getText());
			Entity.setCompanyname(JTFCompanyName.getText());

			Picklist ctc = Picklist.Factory.newInstance();
			ctc.setIntValue(JCBRating.getSelectedIndex()+1);
			Entity.setLeadqualitycode(ctc);
			
			Entity.setTelephone1(JTFBusinessPhone.getText());
			Entity.setEmailaddress1(JTFEmail.getText());
			
			Key id = Key.Factory.newInstance();
			id.setStringValue(this.EntityId);
			Entity.setLeadid(id);
			
			UpdateDocument ud = UpdateDocument.Factory.newInstance();
			Update update = Update.Factory.newInstance();
			update.setEntity(Entity);
			ud.setUpdate(update);
		
			UpdateResponseDocument urd = this.JavaMSCRM.stub.Update(ud, JavaMSCRM.catd, null, null);
			urd.getUpdateResponse();
		}  
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.toString());
		}
		
		new Leads(JavaMSCRM);
		new JavaMSCRMLead(this.JavaMSCRM,this.EntityId);
		dispose();
	}
	
	/* (non-Javadoc)
	 * @see JavaMSCRMForm#deleteRecord()
	 */
	public void deleteRecord(){
		String msg ="Record succesfuly deleted";
		int deleteConfirmation = JOptionPane.showConfirmDialog(null,
				"Are you sure you want to delete this record?",
	       		"Record Deletion Confirmation",  
		        JOptionPane.YES_NO_OPTION);
		if (deleteConfirmation == JOptionPane.YES_OPTION){
			try {
				DeleteDocument dd = DeleteDocument.Factory.newInstance();
				Delete d = Delete.Factory.newInstance();
				d.setId(this.EntityId);
				d.setEntityName(EntityName.LEAD.toString());
				
				dd.setDelete(d);
				
				JavaMSCRM.stub.Delete(dd, JavaMSCRM.catd, null, null);
			}  
			catch (Exception e) {
				msg ="There was a problem while deleting some of the record!";
			}
			
			new Leads(JavaMSCRM);
			dispose();
			JOptionPane.showMessageDialog(null, msg);
		}
	}
}